package info.emamian.droplet.provider;

import info.emamian.droplet.data.DynamoDbSms;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class TwilioAdaptor implements InputSMSAdaptorInterface {
	private static final Logger LOGGER = LoggerFactory.getLogger(TwilioAdaptor.class);
	private static final String PROVIDER_NAME = "twilio.com";

	public TwilioAdaptor() {
	}

	@Override
	public DynamoDbSms convertToDynamoDbSMS(final HttpServletRequest request) {
		DynamoDbSms incoming = convertHttpRequestToDynamoDbSMS(request);
		return incoming;
	}

	private DynamoDbSms convertHttpRequestToDynamoDbSMS(final HttpServletRequest request) {
		// debug
		// if (LOGGER.isDebugEnabled()) {
		// try {
		// Enumeration<?> headerNames = request.getHeaderNames();
		// LOGGER.debug("Headers:");
		// while (headerNames.hasMoreElements()) {
		// String hname = (String) headerNames.nextElement();
		// if (hname == null)
		// continue;
		// LOGGER.debug(" - [{}] -> [{}]", hname,
		// request.getHeader(hname).toString());
		// }
		// }
		// catch (Exception e) {
		// LOGGER.error("Exception , ", e);
		// }
		// }
		Map<String, String> properties = new HashMap<String, String>();

		// try {
		// // store header requests in properties
		// Enumeration<?> c = request.getParameterNames();
		// while (c.hasMoreElements()) {
		// String el = (String) c.nextElement();
		// if (el == null)
		// continue;
		// properties.put(el.toString(), request.getParameter(el));
		// LOGGER.debug("request param [{}] -> [{}]", el,
		// request.getParameter(el));
		// }
		// }
		// catch (Exception e) {
		// LOGGER.error("Exception , ", e);
		// }
		properties.put("remoteAddr", request.getRemoteAddr());
		// extract sms properties
		String from = request.getParameter("From");
		String to = request.getParameter("To");
		String body = request.getParameter("Body");
		DynamoDbSms incomingSMS = new DynamoDbSms(from, to, body, getProviderName(), new Date(), true, properties);
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("TwilioAdaptor converted from request : {}", incomingSMS);
		}
		return incomingSMS;
	}

	@Override
	public String getProviderName() {
		return PROVIDER_NAME;
	}
}
